<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use App\Models\CommentDetail;

class TuWenContent implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $logPrefix = __METHOD__ . ", attribute: $attribute, value: " . json_encode_unicode($value);
        if (empty($value))
        {
            logger("$logPrefix, 就没值, false");
            return false;
        }
        if (is_string($value)) {
            $maybeArr = json_decode($value, true);
            logger("$logPrefix, maybeArr: " . json_encode_unicode($maybeArr));
            if (!is_array($maybeArr)) {
                //原来就是文本
                logger("$logPrefix, 原本就是文本, true");
                return true;
            } else {
                $value = $maybeArr;
            }
        }
        foreach ($value as $item) {
            $type = $item['type'];
            if ($type == CommentDetail::CONTENT_TYPE_TEXT && !empty($item['data']['text'])) {
                logger("$logPrefix, 有文本, true");
                return true;
            }
            if ($type == CommentDetail::CONTENT_TYPE_IMAGE && !empty($item['data'])) {
                logger("$logPrefix, 有图片, true");
                return true;
            }
        }
        logger("$logPrefix, 啥没有, false");
        return false;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return ':attribute 非法或为空';
    }

}
